﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

namespace DL.AI.AIBT.Example
{
    //巡逻
    public class PatrolStrategy : IStrategy
    {
        private readonly Transform m_Entity;
        private readonly NavMeshAgent m_Agent;

        private readonly List<Transform> m_PatrolPoints;
        private readonly float m_PatrolSpeed;
        private int m_CurrentIndex;
        private bool m_IsPathCalculated; //是否正在计算路径

        public PatrolStrategy(Transform entity, NavMeshAgent agent, List<Transform> patrolPoints, float patrolSpeed = 2f)
        {
            m_Entity = entity;
            m_Agent = agent;
            m_PatrolPoints = patrolPoints;
            m_PatrolSpeed = patrolSpeed;
        }

        public Status Process()
        {
            if (m_CurrentIndex == m_PatrolPoints.Count) return Status.Success;

            var target = m_PatrolPoints[m_CurrentIndex];
            m_Agent.SetDestination(target.position);
            m_Entity.LookAt(target);

            if (m_IsPathCalculated && m_Agent.remainingDistance < .1f)
            {
                m_CurrentIndex++;
                m_IsPathCalculated = false;
            }

            if (m_Agent.pathPending)
            {
                m_IsPathCalculated = true;
            }

            return Status.Running;
        }

        public void Reset() => m_CurrentIndex = 0;
    }
}